<template>
  <div>
    <div class="search-bar">
      <!-- 查询条件和新增按钮 -->
      <el-row gutter="20">
        <el-col :span="5">
          <el-input
              v-model="searchName"
              placeholder="请输入类别名称"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="5">
          <el-input
              v-model="searchId"
              placeholder="请输入类别id"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="5">
          <el-select v-model="searchStatus" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="fetchCategories">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="search-bar">
      <el-row gutter="20">
        <el-col :span="4" :offset="15">
          <el-button type="primary" @click="openAddDialog">新增维修类别</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 维修类别表格 -->
    <el-row>
      <el-col :span="24">
        <el-table :data="categories" empty-text="暂无数据" style="width: 60%">
          <el-table-column prop="repairCategoryId" label="类别ID"></el-table-column>
          <el-table-column prop="categoryName" label="类别名称"></el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              {{ scope.row.categoryState === 1 ? "启用" : "禁用" }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button
                  size="mini"
                  :type="scope.row.categoryState === 1 ? 'danger' : 'success'"
                  @click="toggleCategoryState(scope.row)"
              >
                {{ scope.row.categoryState === 1 ? "禁用" : "启用" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialogVisible" width="30%" >
      <el-form :model="addForm" :rules="rules" ref="addFormRef">
        <span class="bold-large">新增类别</span>
        <el-form-item label="类别名称" prop="categoryName">
          <el-input v-model="addForm.categoryName"></el-input>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="cancelAddForm">取 消</el-button>
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" width="30%">
      <el-form :model="editForm" :rules="rules" ref="editForm">
        <span class="bold-large">编辑维修类别</span>
        <el-form-item label="类别名称" prop="categoryName">
          <el-input v-model="editForm.categoryName"></el-input>
        </el-form-item>
        <div class="dialog-footer">
          <el-button @click="cancelEditForm">取 消</el-button>
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 分页组件 -->
    <el-row>
      <el-col :span="24">
        <div class="pagination-container">
          <el-pagination
              :current-page="pageNum"
              :page-size="pageSize"
              :page-sizes="[10, 15, 20]"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  ElTable, ElTableColumn, ElForm,
  ElInput, ElButton, ElPagination, ElDialog,
  ElMessage, ElSelect, ElOption
} from "element-plus";
import axios from "axios";

export default {
  components: {
    ElTable, ElTableColumn, ElForm,
    ElInput, ElButton, ElPagination, ElDialog,
    ElMessage, ElSelect, ElOption
  },
  data() {
    return {
      categories: [],
      total: 0,
      addForm: {
        categoryName: "",
      },
      editForm: {
        repairCategoryId: "",
        categoryName: "",
      },
      searchName: "",
      searchId: "",
      searchStatus: "",
      pageNum: 1,
      pageSize: 10,
      addDialogVisible: false,
      editDialogVisible: false,
      rules: {
        categoryName: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
      },
    };
  },
  methods: {
    async submitAddForm() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const token = localStorage.getItem("token");
            const response = await axios.post("/repaircenter/repairCategory/add", this.addForm, { headers: { token } });

            if (response.data.code === 200) {
              await this.fetchCategories();
              this.resetForm("addFormRef", false);
              this.addDialogVisible = false;
              this.$nextTick(() => ElMessage.success("操作成功"));
            } else {
              ElMessage.error(response.data.msg);
            }
          } catch (error) {
            console.error("Error:", error);
            ElMessage.error("操作失败");
          }
        } else {
          console.log("error submit!!");
        }
      });
    },
    async submitEditForm() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const token = localStorage.getItem("token");
            const response = await axios.put("/repaircenter/repairCategory/updateCategory", this.editForm, { headers: { token } });

            if (response.data.code === 200) {
              await this.fetchCategories();
              this.resetForm("editForm", true);
              this.editDialogVisible = false;
              this.$nextTick(() => ElMessage.success("操作成功"));
            } else {
              ElMessage.error(response.data.msg);
            }
          } catch (error) {
            console.error("Error:", error);
            ElMessage.error("操作失败");
          }
        } else {
          console.log("error submit!!");
        }
      });
    },
    resetForm(formName, isEdit) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this[isEdit ? 'editForm' : 'addForm'] = isEdit ? { repairCategoryId: "", categoryName: "" } : { categoryName: "" };
    },
    async fetchCategories() {
      try {
        const token = localStorage.getItem("token");
        const searchParams = {};

        if (this.searchName) {
          searchParams.categoryName = this.searchName;
        }
        if (this.searchId) {
          searchParams.repairCategoryId = this.searchId;
        }
        if (this.searchStatus !== "") {
          searchParams.categoryState = this.searchStatus;
        }

        searchParams.pageNum = this.pageNum;
        searchParams.pageSize = this.pageSize;

        const response = await axios.post("/repaircenter/repairCategory/list", searchParams, { headers: { token } });

        if (response.data.code === 200) {
          this.categories = response.data.data.list.map(category => ({
            repairCategoryId: category.repairCategoryId,
            categoryName: category.categoryName,
            categoryState: Number(category.categoryState),
          }));
          this.total = response.data.data.total;
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
        ElMessage.error("获取维修类型列表失败");
      }
    },
    async toggleCategoryState(row) {
      try {
        const token = localStorage.getItem("token");
        const url = row.categoryState === 1 ? "/repaircenter/repairCategory/forbiddenStatus" : "/repaircenter/repairCategory/enableStatus";
        const params = { repairCategoryId: row.repairCategoryId };

        const response = await axios.put(url, null, {
          headers: { token },
          params,
        });

        if (response.data.code === 200) {
          this.fetchCategories();
          ElMessage.success("操作成功");
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
        ElMessage.error("操作失败");
      }
    },
    openAddDialog() {
      this.resetForm("addFormRef", false);
      this.addDialogVisible = true;
    },
    openEditDialog(row) {
      this.editForm = {
        repairCategoryId: row.repairCategoryId,
        categoryName: row.categoryName,
      };
      this.editDialogVisible = true;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
          .then((_) => {
            this.resetForm("addFormRef", false);
            this.resetForm("editForm", true);
            done();
          })
          .catch((_) => {});
    },
    cancelAddForm() {
      this.resetForm("addFormRef", false);
      this.addDialogVisible = false;
    },
    cancelEditForm() {
      this.resetForm("editForm", true);
      this.editDialogVisible = false;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.pageNum = 1; // 重置页码
      this.fetchCategories();
    },
    handleCurrentChange(page) {
      this.pageNum = page;
      this.fetchCategories();
    },
  },
  created() {
    this.fetchCategories();
  },
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
}
.bold-large {
  font-weight: bold;
  font-size: 1.5em; /* 调整字体大小，可以根据需要调整 */
}
.search-bar {
  width: 100%;
  margin-bottom: 15px;
}
</style>
